<template>
    <div>
        <div id="message-center" class="align-center">
            <div class="switch flex-center">
                <div style="flex:1" class="cursor align-center pointer" v-if="Type===1" :class="{isactive:Type===1}" @click="toSwitch(1)">
                    <span class="s-16 pointer">消息推送</span>
                    <div class="border-b" :class="{btnisactive:Type===1}"></div>
                </div>
                <div style="flex:1" class="cursor align-center  pointer" v-if="Type===2" :class="{isactive:Type===2}" @click="toSwitch(2)">
                    <span class="s-16 pointer">反馈建议</span>
                    <div class="border-b" :class="{btnisactive:Type===2}"></div>
                </div>
            </div>
            <div class="message-content" v-show="Type===1" ref="messageContent">
                <div class="messgae-item" v-for="(item, index) in allPostMessage" :key="index">
                    <span class="time s-12">{{item.modifyTime}}</span>
                    <div class="item-content">
                        <div id="avatar">
                            <img :src="avatarImg" alt="">
                        </div>
                        <div id="content" class=" align-center pointer" @click="showdetail(index)">
                            <img class="left" src="../../../assets/img/home/message-left.png" alt="">
                            <div class="title s-14 pointer">
                                <div class="title-content pointer" v-html="item.title"></div>
                                <!-- <div class="detail s-12 pointer">详情<img class="detail-img" src="../../../assets/img/home/message-right.png" alt=""></div> -->
                            </div>
                            <div class="thump pointer" v-if="item.thumb">
                                <img class="logo" src="../../../assets/img/home/bos_fornav.png" alt="">
                                <img class="thump-img" :src="item.thumb" alt="">
                            </div>
                            <div class="unread-message pointer" v-if="item.isRead==='1'"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="user-feedback align-between" v-show="Type===2">
                <div class="contact flex-center">
                    <img class="code" :src="codeImg" alt="">
                    <div class="servicer">
                        <span class="s-14 t-color-m">公众号：美丽科学教学平台</span>
                        <div class="s-12 t-color-c" style="margin-top:9px">如需帮助，请扫码关注公众号，留言咨询在线客服。</div>
                    </div>
                </div>
                <!-- <div class="feedback-container" ref="feedbackContainer" v-infinite-scroll="loadMore" infinite-scroll-distance="5" infinite-scroll-disabled="dontLoadMore"> -->
                <div class="feedback-container" ref="feedbackContainer">
                    <div v-for="(item, index) in feedbackNumsList" :key="index">
                        <div class="align-center chat-content">
                            <span class="time s-12">{{item.createTime}}</span>
                            <div class="custorm-content">
                                <div id="content" class="customer-message" style="position:relative">
                                    <img class="right" src="../../../assets/img/home/chat-right.png" alt="">
                                    <div class="s-14 ">
                                        <div class="title-content" >{{item.description}}</div>
                                    </div>
                                    <span  :class="[item.isResponse === '1' ? 'Responsed' : 'notRes']" style="">已处理</span>
                                </div>
                                <!-- </div> -->
                                <div id="avatar" class="ava-right">
                                    <img src="../../../assets/img/home/servicer-avatar.png" alt="">
                                </div>
                            </div>
                        </div>
                        <div class="align-center chat-content" v-if="item.answer">
                            <span class="time s-12">{{item.createTime}}</span>
                            <div class="servicer-content">
                                <div id="avatar">
                                    <img :src="avatarImg" alt="">
                                </div>
                                <div id="content">
                                    <img class="left" src="../../../assets/img/home/message-left.png" alt="">
                                    <div class="title s-14 ">
                                        <div class="title-content">感谢您的反馈，您也可以扫码关注上方的公众号，留言咨询在线客服。</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="wanttosay-container">
                    <input class="wanttosay" type="text"  v-model="feedbackMessage" @keyup.enter="postFeedback"/>
                    <div class="say-btn pointer s-14" @click="postFeedback">提交</div>
                </div>
            </div>
        </div>
        <message-detail @closeMessageCenter="closeMessageCenter" v-if="isShowdetail" :bookId="bookId" :lessonId="allPostMessage[Messageindex].lessonId" :msgUrl="allPostMessage[Messageindex].msgUrl" :isShowdetail.sync="isShowdetail"></message-detail>
    </div>
</template>

<script>
// import { custormerFeedback, getCustormerFeedbackNums } from '../../../api/user'
import moment from 'moment';
import userApi from '../../../api/user'
import { SqlLib } from '../../../../../../static/lib/sqlite/SqlLib'
import { SqlLibUser } from '../../../../../../static/lib/sqlite/service/SqlLibUser'
import messageDetail from './MessageDetail'
import bus from '../../../assets/js/bus';
import { Ini } from '../../../utils/ini';
export default {
    props: ['toBeReadNum', 'messageCenterIsShow',],
    props:{
        Type:{
            type:Number,
            required:true,
        },
        
    },
    components: { messageDetail },
    data() {
        return {
            active:0,
            pageCount: 1,
            pageSize: 10,
            userId: '',
            feedbackNumsList: [],
            feedbackMessage: '',
            feedBackAnswerList: [],
            pages: 0,
            isShowdetail: false,
            allPostMessage: [],
            Messageindex: 0,
            eduLevel: Ini.readIni('data', 'eduLevel'),
        }
    },
    created() {
        this.getPages()
    },
    computed: {
        bookId() {
            return this.allPostMessage[this.Messageindex].bookId
        },
        codeImg() {
            if (this.eduLevel === 'primary') {
                return require('../../../assets/img/home/wechatqr.png')
            } else {
                return require('../../../assets/img/home/wechatqr.png')
            }
        },
        avatarImg() {
            if (this.eduLevel === 'primary') {
                return require('../../../assets/img/home/message-avatar.png')
            } else {
                return require('../../../assets/img/home/ava-ms.png')
            }
        }
    },
    mounted() {
        // this.active = this.Type
        // console.log(this.active);
        this.$nextTick(() => {
            let sqlLib = SqlLib.getInstance(window.$DBDIR)
            this.userId = SqlLibUser.queryCurrentUser(sqlLib).id
            this.getAllPostMessage()
        })
        // let dom = document.getElementsByClassName('message-content')[0]
        // dom.scrollTop = dom.scrollHeight - dom.clientHeight
        // let haveNewMessage = new BroadcastChannel('push-messgae-has-been-updated')
        // haveNewMessage.addEventListener('message', async e => {
        //     console.log("接收到消息")
        //     if (e.data.updateNum) {
        //         this.getAllPostMessage()
        //     }
        // })
    },
    methods: {
        async showdetail(index) {
            if (this.isShowdetail) return
            this.Messageindex = index
            this.isShowdetail = true
            if (this.allPostMessage[index].isRead === '1') return
            let res = await userApi.changeMessageStatus({ msgId: this.allPostMessage[index].messageId })
            if (res.code === '0') {
                this.allPostMessage[index].isRead = '1'
                let isAllreadArry = this.allPostMessage.filter(v => {
                    return v.isRead === '0'
                })
                this.$emit('update:toBeReadNum', isAllreadArry.length)
            }
        },
        closeMessageCenter() {
            this.$emit('update:messageCenterIsShow', false)
        },
        toSwitch(val) {
            this.Type = val
            if (val === 2) {
                this.scorllToBottom()
            }
        },
        async getAllPostMessage() {
            let allmessage = await userApi.getAllPostMessage()
            if (allmessage.code === '0') {
                if (allmessage.returnValue) {
                    let noAllread = allmessage.returnValue.filter(message => {
                        return message.isRead === '0'
                    })
                    this.$emit('update:toBeReadNum', noAllread.length)
                    this.allPostMessage = allmessage.returnValue
                    this.scorllToBottom()
                }
            }
        },
        pullOnLoading(e) {
            if (this.time) {
                clearTimeout(this.time)
            }
            this.time = setTimeout(async () => {
                let height = e.target.scrollHeight
                let top = e.target.scrollTop
                if (top === 0) {
                    this.pageCount = (this.pageCount - 1) || 1
                    await this.getCustormerFeedbackNums(this.pageCount)
                    this.keepScorllPosition(height)
                }
            }, 300);
        },
        async getPages() {
            let res = await userApi.getCustormerFeedbackNums({ pageCount: this.pageCount, pageSize: this.pageSize, userId: this.userId })
            if (res.code === '0') {
                console.log(res);
                this.pageCount = this.pages = parseInt( res.returnValue.pages)
                await this.getCustormerFeedbackNums(this.pages)
                if (this.pages === 1) return
                if (this.feedbackNumsList.length <= 8) {
                    this.pageCount--
                    this.getCustormerFeedbackNums(this.pages - 1)
                }
                this.$refs.feedbackContainer.addEventListener('scroll', this.pullOnLoading)
            }
        },
        async getCustormerFeedbackNums(pages) {
            if (pages === 1) {
                this.$refs.feedbackContainer.removeEventListener('scroll', this.pullOnLoading)
            }
            this.dontLoadMore = true
            let FeedbackNums = await userApi.getCustormerFeedbackNums({ pageCount: pages, pageSize: this.pageSize, userId: this.userId })
            if (FeedbackNums && FeedbackNums.code === '0') {
                this.feedbackNumsList.unshift(...FeedbackNums.returnValue.records)
            }
        },
        async postFeedback() {
            let res = await userApi.custormerFeedback({ feedBacks: this.feedbackMessage })
            if (res.code === '0') {
                this.answerFeedback()
                this.scorllToBottom()
            }
        },
        //自动回复聊天
        answerFeedback() {
            let time = moment().format("YYYY-MM-DD HH:mm:ss");
            this.feedbackNumsList.push({ createTime: time, description: this.feedbackMessage, answer: true })
            this.feedbackMessage = ''
        },
        //滚动条置底
        scorllToBottom() {
            this.$nextTick(() => {

                if (this.Type === 1) {
                    if (this.$refs.messageContent) {
                        this.$refs.messageContent.scrollTop = this.$refs.messageContent.scrollHeight - this.$refs.messageContent.clientHeight
                    }
                } else {
                    if (this.$refs.feedbackContainer) {
                        this.$refs.feedbackContainer.scrollTop = this.$refs.feedbackContainer.scrollHeight - this.$refs.feedbackContainer.clientHeight
                    }
                }

            })
        },
        //上拉加载保持滚动条不变
        keepScorllPosition(height) {
            this.$nextTick(() => {
                console.log('跟新后', this.$refs.feedbackContainer.scrollHeight)
                this.$refs.feedbackContainer.scrollTop = this.$refs.feedbackContainer.scrollHeight - height
            })
        }
    },
}
</script>

<style lang="scss">
#message-center {
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    overflow: hidden;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 10px 10px 0px rgba(0, 0, 0, 0.05);
    border-radius: 8px;
    padding-top: 16px;
    padding-bottom: 10px;
    .title-content {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 3;
        overflow: hidden;
        margin-bottom: 5px;
    }
    .blod-font {
        font-weight: bold;
    }
    .switch {
        width: 100%;
        border-bottom: 1px solid rgba(220, 223, 231, 1);
        color: #303133;
        .border-b {
            width: 28px;
            height: 2px;
            background-color: transparent;
            margin-top: 13px;
        }
        .isactive {
            color: #4894ff;
        }
        .btnisactive {
            background-color: rgba(72, 148, 255, 1);
        }
    }
    .message-content {
        padding-top: 20px;
        flex: 1;
        overflow: auto;
        width: 100%;
        overflow-x: hidden;
        .item-content {
            display: flex;
            justify-content: center;
            align-items: flex-start;
            // &:not(:last-child) {
            //     margin-bottom: 20px;
            // }
            margin-bottom: 20px;
        }
    }
    .time {
        color: #909399;
        display: block;
        text-align: center;
        margin-bottom: 13px;
    }
    #avatar {
        margin-right: 14px;
        &.ava-right {
            margin-left: 14px;
            margin-right: 0;
        }
        img {
            width: 37px;
            height: 37px;
        }
    }
    .Responsed{
        text-align:center;
        width: 50px;
        height: 16px;
        font-size: 10px;
        // padding-bottom:5px;
        background: #9DCDFC;
        border-radius: 4px 0px 4px 0px;
        position:absolute;
        display: flex;
        align-items: center;
        justify-content: center;
        bottom:0px;
        right:0px;
    }
    .notRes{
        display: none;
    }
    #content {
        max-width: 270px;
        min-width: 90px;
        // min-height: 56px;
        background: rgba(238, 243, 250, 1);
        border-radius: 8px;
        position: relative;
        padding: 16px 20px;
        font-size: 14px;
        text-align: center;
        
        .unread-message {
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            background-color: rgba(244, 244, 244, 0.7);
        }
        &.customer-message {
            color: #fff;
            background: #4894ff;
        }
        .left {
            width: 8px;
            height: 12px;
            position: absolute;
            left: 0;
            top: 12px;
            transform: translate(-100%, 0);
        }
        .right {
            width: 8px;
            height: 12px;
            position: absolute;
            right: 0;
            top: 12px;
            transform: translate(100%, 0);
        }
        .title {
            color: #303133;
            position: relative;
            width: 100%;
        }
        .detail {
            position: absolute;
            bottom: 0;
            right: 0;
            color: #4894ff;
            z-index: 999;
            .detail-img {
                width: 7px;
                height: 9px;
                vertical-align: middle;
                margin-left: 5px;
            }
        }
        .thump {
            margin-top: 20px;
            width: 230px;
            height: 130px;
            border-radius: 8px;
            position: relative;
            .thump-img {
                width: 100%;
                height: 100%;
                border-radius: 8px;
            }
            .logo {
                width: 64px;
                height: 24px;
                top: 8px;
                right: 10px;
                position: absolute;
            }
        }
    }
    .chat-content {
        margin-bottom: 26px;
    }
    .feedback-container {
        flex: 1;
        width: 100%;
        overflow: auto;
        & > div:first-child {
            margin-top: 30px;
        }
    }
    .custorm-content {
        display: flex;
        justify-content: center;
        align-self: flex-end;
        padding-right: 20px;
    }
    .servicer-content {
        display: flex;
        justify-content: center;
        align-self: flex-start;
        padding-left: 20px;
    }
    .user-feedback {
        flex: 1;
        width: 100%;
        position: relative;
        .contact {
            width: 100%;
            height: 100px;
            background: rgba(247, 251, 255, 1);
            padding: 18px 20px;
            .code {
                width: 64px;
                height: 64px;
                margin-right: 13px;
            }
        }
        .wanttosay-container {
            height: 48px;
            width: 100%;
            position: relative;
            padding: 0 20px;
            .say-btn {
                position: absolute;
                top: 14px;
                right: 36px;
                color: #409eff;
            }
        }
        .wanttosay {
            width: 100%;
            height: 100%;
            background: rgba(234, 240, 246, 1);
            border-radius: 8px;
            outline: none;
            border: none;
            padding-left: 14px;
            padding-right: 50px;
        }
    }
}
@media screen and(max-height: 800px) {
    #message-center {
        transform: scale(0.8, 0.8);
        top: -13vh;
        left: -3vw;
        .user-feedback {
            .contact {
                .code {
                    width: 75px;
                    height: 75px;
                }
            }
        }
    }
}
</style>    